package db.seed;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mai4j.maiadmin.setup.Helper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.Map;

import static com.mai4j.maiadmin.generated.Tables.LOCATION;
import static com.mai4j.maiadmin.generated.Tables.LOCATION_DESCRIPTION;
import static org.jooq.impl.DSL.using;


/**
 * 初始化国家和地区
 */
@Slf4j
public class V20230409085012__Insert_Location extends BaseJavaMigration {

    @SneakyThrows
    @Override
    public void migrate(Context context) {
        LinkedHashMap<String, LinkedHashMap<String, String>> locations = new Gson().fromJson(IOUtils.resourceToString("/db/locations.json", StandardCharsets.UTF_8),
                new TypeToken<LinkedHashMap<String, LinkedHashMap<String, String>>>() {
                }.getType());
        int i = 0;
        for (Map.Entry<String, LinkedHashMap<String, String>> objectEntry : locations.entrySet()) {
            String code = objectEntry.getKey();
            long locationId = Helper.next();
            using(context.getConnection())
                    .insertInto(LOCATION)
                    .columns(
                            LOCATION.LOCATION_ID,
                            LOCATION.CODE,
                            LOCATION.SORT_ORDER,
                            LOCATION.STATUS,
                            LOCATION.DATE_ADDED,
                            LOCATION.DATE_MODIFIED
                    )
                    .values(locationId,
                            code,
                            i++,
                            (byte) 1,
                            LocalDateTime.now(),
                            LocalDateTime.now()).execute();
            LinkedHashMap<String, String> names = objectEntry.getValue();
            for (Map.Entry<String, String> nameEntry : names.entrySet()) {
                using(context.getConnection()).insertInto(LOCATION_DESCRIPTION).columns(
                        LOCATION_DESCRIPTION.LOCATION_ID,
                        LOCATION_DESCRIPTION.LANGUAGE_CODE,
                        LOCATION_DESCRIPTION.NAME
                ).values(locationId, nameEntry.getKey(), nameEntry.getValue()).execute();
            }
        }
    }
}
